from flask import Flask, render_template, request, session
from markupsafe import escape
from vsearch import search4letters
from DBcm import UseDatabase
from checker import check_logged_in

# import mysql.connector

dbconfig = {
    "host": "127.0.0.1",
    "user": "vsearch",
    "password": "vsearchpasswd",
    "database": "vsearchlogDB",
}

app = Flask(__name__)
app.secret_key = '404'


def log_request(req: "flask_request", res: str) -> None:
    with UseDatabase(dbconfig) as cursor:
        _SQL = """insert into log
        (phrase, letters, ip, browser_string, results)
        values
        (%s,%s,%s,%s,%s)"""
        cursor.execute(
            _SQL,
            (
                req.form["phrase"],
                req.form["letters"],
                req.remote_addr,
                "browser test",  # 这里用  req.user_agents.browser 会报错，先搁置问题
                res,
            ),
        )


@app.route("/search4", methods=["POST"])
def do_search() -> "html":
    phrase = request.form["phrase"]
    letters = request.form["letters"]
    title = "Here are your results:"
    results = str(search4letters(phrase, letters))
    log_request(request, results)
    return render_template(
        "results.html",
        the_title=title,
        the_phrase=phrase,
        the_letters=letters,
        the_results=results,
    )


@app.route("/")
@app.route("/entry")
def entry_page() -> "html":
    return render_template(
        "entry.html", the_title="Welcome to search4letters on the web!"
    )


@app.route("/viewlog")
@check_logged_in
def view_the_log() -> "html":
    # update start
    with UseDatabase(dbconfig) as cursor:
        _SQL = """select phrase,letters,ip,browser_string,results from log"""
        cursor.execute(_SQL)
        contents = cursor.fetchall()
    titles = ("Phrase", "Letters", "Remote_addr", "User_agent", "Result")
    # update end
    return render_template(
        "viewlog.html",
        the_title="View Log",
        the_row_titles=titles,
        the_data=contents,
    )


@app.route("/login")
def do_login() -> str:
    session["logged_in"] = True
    return "You are now logged in."


@app.route("/logout")
def do_logout() -> str:
    session.pop("logged_in")
    return "You are now logged out."


if __name__ == "__main__":
    app.run(debug=True)
